/**
 * 
 */
package controler;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;



/**
 * @author z0nk
 *
 */


public class Allegro extends AProvider {

	/**
	 * 
	 */
	
	public Allegro() {
		loginPage = "http://allegro.pl/myaccount/";
	}
	@Override
	public String GetName(Item p) throws ItemNotFound {
		
		String page = getPage(p.getUrl());
		
		Document doc = Jsoup.parse(page);
		Element link = doc.select("h1").first();
		if(link == null) throw new ItemNotFound();
		
		
		return link.text();

	}
	
	@Override
	public Float GetPrice(Item p) {
		
		String page = getPage(p.getUrl());	
		Document doc = Jsoup.parse(page);
		Element tmp = doc.getElementById("siBidForm2");
		
		if(tmp != null){
			Element elel = tmp.getElementsByAttributeValue("name", "amount").first();
			String tmpprice = elel.val().replace(',', '.');
			return Float.parseFloat(tmpprice);
		}
		
		return null;
	}
	
	@Override
	public Date GetFinishDate(Item p) throws ItemIsBuyNow, ItemAuctionFinished{
		String page = getPage(p.getUrl());
		
		//"left smaller timeInfo"
		Document doc = Jsoup.parse(page);
		
		Element link = doc.getElementsByAttributeValue("class","left smaller timeInfo").first();
		Date data = null;
		String dtext = link.text();
		if(!dtext.contains("Zakończona")){
			
			Element auction = doc.getElementsByAttributeValue("id", "siBidForm2").first();
			Elements typeauctions = auction.getElementsByTag("form");
			
			Boolean licitation = false;
			
			for (Element type : typeauctions) {
				if(type.attr("action").equals("/pre_bid.php")) licitation = true;
			}
			
			if(!licitation){ throw new ItemIsBuyNow(); }
			
			int pos1 = dtext.indexOf('(')+1;
			int pos2 = dtext.indexOf(')');
			
			String date=dtext.substring(pos1, pos2);
			if(date.startsWith(" ")){ date=dtext.substring(pos1+1, pos2); } 
			String[] datetext = date.replace(",", "").split(" ");
			
		Integer iday = Integer.parseInt( datetext[0].trim() );
		String smonth = datetext[1].trim();
		String day="";
		
		PLMonths tmonth = PLMonths.toMonth(smonth);
		Integer nmonth=tmonth.ordinal();
		String month="";
		if(nmonth < 10){
			month = "0"+nmonth;
		}else{
			month = nmonth.toString();
		}
		
		if(iday < 10){
			day = "0"+iday;
		}else{
			day = iday.toString();
		}
		
		int year = 2012;
		String mydate= ""+ year +"-" + month +"-"+day+ " "+datetext[2].trim(); 
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			data = format.parse(mydate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		}else{
			throw new ItemAuctionFinished("Auction Finished!");
		}
		
		return data;
	}
	
	@Override
	public Boolean Buy(Item p, Credentials c) {
		
		if(super.Buy(p, c)){
			System.out.println("Allegro Buy!");
		}else{
			return false;
		}
		
		return true;
	}
	
	@Override
	public HttpClient Login(Credentials cred) throws LoginException {
		// TODO wrong user exception
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		DefaultHttpClient client = new DefaultHttpClient();
		//String page = getPage(loginPage);
		HttpGet getloginPage = new HttpGet(loginPage);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		Document doc;
		try {
			doc = Jsoup.parse(client.execute(getloginPage,responseHandler));
			Element form = doc.getElementById("form_login");
			Elements inputs = form.getElementsByAttributeValue("type", "hidden");

			for (Element el : inputs) {
				nameValuePairs.add(new BasicNameValuePair(el.attr("name"), el.attr("value")));
			}
			
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		nameValuePairs.add(new BasicNameValuePair("user_login", cred.getLogin()));
	    nameValuePairs.add(new BasicNameValuePair("user_password", cred.getPassword()));
		
		HttpPost loginform = new HttpPost("https://ssl.allegro.pl/login.php");
		

		//client.getParams().setParameter("CONNECTION_MANAGER_TIMEOUT ", 1000);
		//client.getParams().setParameter("http.protocol.allow-circular-redirects", true);
		//client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
		
		
		
		client.setRedirectStrategy(new DefaultRedirectStrategy(){
			@Override
			public boolean isRedirected(HttpRequest request, HttpResponse response, org.apache.http.protocol.HttpContext context)  {
				boolean isRedirect = false;
				
		        try {
		            isRedirect = super.isRedirected(request, response, context);
		        } catch (ProtocolException e) {
		            e.printStackTrace();
		        }
		        

		        if (!isRedirect) {
		            int responseCode = response.getStatusLine().getStatusCode();
		            if (responseCode == 301 || responseCode == 302) {
		                return true;
		            }
		        }
		        return false;
		    }
		});
		

		try {

			UrlEncodedFormEntity postdata = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
			loginform.setEntity(postdata);
			loginform.addHeader("Referer", loginPage);
			
			HttpResponse response = client.execute(loginform);
			
				doc = Jsoup.parse(EntityUtils.toString(response.getEntity()));
				
				Element derror = doc.getElementsByAttributeValue("class", "error").first();
				Element msgnode = doc.getElementsByAttributeValue("class", "error").first();
				if(derror != null) throw new LoginException(derror.getElementsByTag("b").first().text());
				else if(msgnode != null) throw new LoginException(msgnode.getElementsByTag("b").first().text());
				
				Element link = doc.getElementsByTag("a").first();
				//if(link.attr("href").equals("#")) throw new LoginException("Wrong username or password");
				
				HttpPost acc = new HttpPost(link.attr("href"));
			do{	
				EntityUtils.consume(response.getEntity());
				response = client.execute(acc);
				if(response.getStatusLine().getStatusCode() != 200){
					System.out.println(response.getStatusLine());
					acc = new HttpPost("http://allegro.pl" + response.getFirstHeader("location").getValue());
				}else{
					System.out.println(EntityUtils.toString(response.getEntity()));
				}
			}while(response.getStatusLine().getStatusCode() != 200);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (LoginException e){
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e){
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
		
		}
		
		
		
		
		return client;
	}
	@Override
	public Calendar GetServerDate() {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://www.allegro.pl");
		Header hdate = null;
		Calendar cal = Calendar.getInstance();
		try {
			HttpResponse response = client.execute(get);
			hdate = response.getHeaders("Date")[0];
			cal.setTime( DateUtils.parseDate(hdate.getValue()));
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DateParseException e) {
			e.printStackTrace();
		}
		
		return cal;
	}

}
